package com.bitcat.firstapp.demo.handlerdemo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivityHandlerDemoBinding
import com.bitcat.firstapp.demo.intentdemo.Person
import kotlin.concurrent.thread

class HandlerDemoActivity : AppCompatActivity() {

    private val binding: ActivityHandlerDemoBinding by lazy {
        ActivityHandlerDemoBinding.inflate(layoutInflater)
    }

    //创建handler
    private val handler = object : Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            println("handleMessage 当前线程：" + Thread.currentThread().name)
            when(msg.what){
                0 -> {
                    binding.contentTv.text = "sendEmptyMessage"
                }
                1 ->{
                    val person = msg.obj as Person
                    binding.contentTv.text = "sendMessage ${person.name} ${person.age}"
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 300, systemBars.right, systemBars.bottom)
            insets
        }

        setListeners()
    }

    private fun setListeners() {
        binding.s1Btn.setOnClickListener {
            thread {
                println("thread 当前线程：" + Thread.currentThread().name)
//                handler.sendEmptyMessage(0)
                handler.sendEmptyMessageDelayed(0,2000)
            }
        }

        binding.s2Btn.setOnClickListener {
            thread {
                val message = Message.obtain()
                message.what = 1
                message.obj = Person("张三", 18)
                handler.sendMessage(message)
            }
        }

        binding.s3Btn.setOnClickListener {
            thread {
                println("post1 当前线程：" + Thread.currentThread().name)    //post1 当前线程：Thread-5
                handler.post {
                    println("post2 当前线程：" + Thread.currentThread().name) //post2 当前线程：main
                    binding.contentTv.text = "post"
                }
            }
        }
    }
}